package com.jy.datapipeline.export.quartz;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.jy.datapipeline.common.util.BeanFactoryUtil;
import com.jy.datapipeline.export.entity.DataStoreInfoModel;
import com.jy.datapipeline.export.entity.ExpRuleModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteDetailLogModel;
import com.jy.datapipeline.export.properties.QuartzProperties;
import com.jy.datapipeline.export.service.DataStoreInfoService;
import com.jy.datapipeline.export.service.ExpRuleService;
import com.jy.datapipeline.export.service.ExpTaskExecuteDetailLogService;
import com.jy.datapipeline.export.service.ExpTaskExecuteLogService;
import com.jy.datapipeline.common.util.FtpUtil;
import com.jy.datapipeline.common.util.TEAUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
//@Component
public class JobDetailRestryFileToSftpHandler extends QuartzJobBean {
//    @Autowired
//    private  ExpTaskService expTaskService;
//    @Autowired
//    private  ExpTaskExecuteLogService expTaskExecuteLogService;
//    @Autowired
//    private  ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService;
//    @Autowired
//    private  DataStoreInfoService dataStoreInfoService;
//    @Autowired
//    private  ExpRuleService ruleService;
//    @Value("${config.localStorePath}")
//    public   String localStorePath;
//    public JobDetailRestryFileToSftpHandler(ExpTaskService expTaskService,
//        ExpTaskExecuteLogService expTaskExecuteLogService,
//        ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService,
//        DataStoreInfoService dataStoreInfoService, ExpRuleService ruleService) {
//        this.expTaskService = expTaskService;
//        this.expTaskExecuteLogService = expTaskExecuteLogService;
//        this.expTaskExecuteDetailLogService = expTaskExecuteDetailLogService;
//        this.dataStoreInfoService = dataStoreInfoService;
//        this.ruleService = ruleService;
//    }


    @Override
    protected void executeInternal(JobExecutionContext context) {
        ExpTaskExecuteLogService expTaskExecuteLogService = BeanFactoryUtil.getBean(ExpTaskExecuteLogService.class);
        ExpTaskExecuteDetailLogService expTaskExecuteDetailLogService = BeanFactoryUtil.getBean(ExpTaskExecuteDetailLogService.class);
        DataStoreInfoService dataStoreInfoService = BeanFactoryUtil.getBean(DataStoreInfoService.class);
        ExpRuleService ruleService = BeanFactoryUtil.getBean(ExpRuleService.class);
        QuartzProperties quartzProperties = BeanFactoryUtil.getBean(QuartzProperties.class);

        try{

            List<ExpTaskExecuteDetailLogModel> etedlmList= expTaskExecuteDetailLogService.findByExpStatus(-3,0);//sftp上传error
            if(etedlmList.size()>0){
                AtomicReference<ChannelSftp> channelSftp=new AtomicReference<>();

                etedlmList.forEach( etedl-> {

                    //检查是否有反馈文件
                    DataStoreInfoModel dsim = dataStoreInfoService.findByStoreId(
                        etedl.getStoreId());
                    ExpRuleModel expRuleModel= ruleService.findByRuleId(etedl.getRuleId());
                    ExpTaskExecuteDetailLogModel expTaskExecuteDetailLogModel = new ExpTaskExecuteDetailLogModel();

                    try {
                        channelSftp.set(FtpUtil.connectBySftp(dsim.getHost(),
                            dsim.getUserName(),
                            TEAUtil.decode(dsim.getPassword())));
                        log.info("retry sftp connection datafile:{}",etedl.getDataFilePath());
                        etedl.setExpStatus(3);//上传中
                        etedl.setSftpStartTime(new Date());
                        expTaskExecuteDetailLogService.updateExpStatus(etedl);
                        if(etedl.getDataFilePath()!=null){
                            String[] dataFilePathStr=etedl.getDataFilePath().split(",");
                            for(int i=0;i<dataFilePathStr.length;i++){
                                //String dataFilePath=dataFilePathStr[i];
                                FtpUtil.uploadFileBySftp(dataFilePathStr[i],dsim.getRemotePath(),
                                    channelSftp.get(), expRuleModel.getIsFile());
                            }
                            String verifyFilePath=quartzProperties.getLocalStorePath()+"/"+etedl.getDataFileNamePrefix()+".verf";
                            FtpUtil.uploadFileBySftp(verifyFilePath,dsim.getRemotePath(),
                                channelSftp.get(), expRuleModel.getIsFile());
                            FtpUtil.disconnect(channelSftp.get());
                        }

                        // String dataFilePath=localStorePath+"/"+etedl.getDataFileNamePrefix()+".dat";




                        etedl.setExpStatus(4);//上传完成
                        etedl.setSftpeEndtime(new Date());
                        expTaskExecuteDetailLogService.updateExpStatus(etedl);
                        expTaskExecuteLogService.updateExeuceStatus(etedl.getTaskExecutelogLogId(),1,0,"","");
                    } catch (JSchException | SftpException e) {
                        log.info("retry sftp error ",e);
                        etedl.setErrorMsg(e.getMessage());
                        etedl.setExpStatus(-3);//上传异常
                        etedl.setSftpeEndtime(new Date());
                        expTaskExecuteDetailLogService.updateExpStatus(etedl);
                        FtpUtil.disconnect(channelSftp.get());
                    }

                });
            }
        }catch (Exception e){
            log.error("JobDetailExportTaskHandler error",e);
        }
    }
}
